﻿using HandyControl.Controls;
using log4net;
using Newtonsoft.Json;
using PlaceOrder_Admin.Events;
using PlaceOrder_Admin.Extensions;
using PlaceOrder_Admin.Models.Common;
using PlaceOrder_Admin.Models.Config;
using PlaceOrder_Admin.Views;
using PlaceOrder_Core.Helper;
using PlaceOrder_Core.PlaceOrderModels;
using PlaceOrder_Core.Services.Instances;
using PlaceOrder_Core.Services.Interfaces;
using PlaceOrder_Shared.Models.Daily;
using Prism.Commands;
using Prism.DryIoc;
using Prism.Events;
using Prism.Mvvm;
using Prism.Regions;
using Prism.Services.Dialogs;
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using Application = System.Windows.Application;

namespace PlaceOrder_Admin.ViewModels
{
    internal class MainViewModel : BindableBase, IConfigureService
    {
        #region 静态单例窗口
        public static ChatMessageAdminWindow _chatMessageView; // 声明一个私有字段存储单例
        #endregion


        private readonly ILog _logger;
        private readonly IRegionManager _regionManager;
        private readonly IDialogService _dialogService;
        private readonly IData _data;

        public event Action<IDialogResult> RequestClose;

        public string Title { get; set; } = "全益订单管理端 - " + UserHelper.NickName;
        public DelegateCommand<MenuBar> NavigateCommand { get; private set; }
        public DelegateCommand<string> CreateViewCommand { get; private set; }
        public DelegateCommand SaveLocationConfigCommand { get; private set; }
        public MainViewModel(ILog logger, IEventAggregator aggregator, IRegionManager regionManager, IDialogService dialogService)
        {
            //注册提示消息
            _dialogService = dialogService;
            this._regionManager = regionManager;
            CreateMenuBar();

            NavigateCommand = new DelegateCommand<MenuBar>(Navigate);
            CreateViewCommand = new DelegateCommand<string>(CreateView);
            aggregator.GetEvent<MessageEvent>().Subscribe(arg =>
            {

                //Growl.SuccessGlobal("11111",);
                Growl.Info(arg.Message, "SuccessMsg");


            });
            
        }

        private async void CreateView(string view)
        {
            switch (view)
            {
                //case "Order":
                //    await CreateOrderViewAsync();
                //    break;
                //case "LongHu":
                //    await CreateLongHuViewAsync();
                //    break;
                default:
                    return;
            }
        }


        public void Configure()
        {
            //默认导航到IndexView首页
            _regionManager.Regions[PrismRegionManager.MainViewRegionName].RequestNavigate("IndexAdminView");
        }

        #region 依赖属性
        public ObservableCollection<MenuBar> MenuBars
        {
            get { return menuBars; }
            set { menuBars = value; RaisePropertyChanged(); }
        }
        private ObservableCollection<MenuBar> menuBars;


        void CreateMenuBar()
        {
            MenuBars = new ObservableCollection<MenuBar>();
            MenuBars.Add(new MenuBar() { Icon = "\uE18F", Title = "实时交易", NameSpace = "IndexAdminView" });
            MenuBars.Add(new MenuBar() { Icon = "\uE8F2", Title = "聊天列表", NameSpace = "ChatAdminMessageView" });
            //MenuBars.Add(new MenuBar() { Icon = "\uE95D", Title = "备忘录", NameSpace = "MemoView" });
            MenuBars.Add(new MenuBar() { Icon = "\uE211", Title = "历史盈亏", NameSpace = "SettingsView" });
            MenuBars.Add(new MenuBar() { Icon = "\uE211", Title = "交易复盘", NameSpace = "SettingsView" });
            MenuBars.Add(new MenuBar() { Icon = "\uE211", Title = "审议记录", NameSpace = "ReviewView" });

        }
        #endregion


        /// <summary>
        /// 导航
        /// </summary>
        /// <param name="obj"></param>
        private void Navigate(MenuBar obj)
        {
            if (obj == null || string.IsNullOrWhiteSpace(obj.NameSpace))
                return;

            _regionManager.Regions[PrismRegionManager.MainViewRegionName].RequestNavigate(obj.NameSpace);
        }

        /// <summary>
        /// 打开默认窗口
        /// </summary>
        //public async static void ShowOrderView()
        //{
        //    try
        //    {
        //        string filePath = "PlaceOrderViewConfig.json";
        //        if (File.Exists(filePath))
        //        {
        //            string json = await File.ReadAllTextAsync(filePath);

        //            var config = JsonConvert.DeserializeObject<WindowConfig>(json);
        //            if (config == null || config.WindowPositions == null) return;

        //            var orderViews = config.WindowPositions.ContainsKey("OrderView") ? config.WindowPositions["OrderView"] : new List<WindowPosition>();
        //            var longHuView = config.WindowPositions.ContainsKey("LongHuView") ? config.WindowPositions["LongHuView"] : new List<WindowPosition>();
        //            var onHoldView = config.WindowPositions.ContainsKey("OnHoldView") ? config.WindowPositions["OnHoldView"] : new List<WindowPosition>();
        //            var messageView = config.WindowPositions.ContainsKey("ChatMessageView") ? config.WindowPositions["ChatMessageView"] : new List<WindowPosition>();

        //            // 使用并行任务处理多个窗口的初始化和显示
        //            var tasks = new List<Task>();

        //            // 在UI线程上创建并显示窗口
        //            await PrismApplication.Current.Dispatcher.InvokeAsync(async () =>
        //            {
        //                for (int i = 0; i < orderViews.Count; i++)
        //                {
        //                    var orderView = orderViews[i];
        //                    var orderWindow = new OrderView
        //                    {
        //                        Title = $"{UserHelper.NickName} 下单窗口{i + 1}",
        //                        Left = orderView.Left,
        //                        Top = orderView.Top,
        //                        Width = orderView.Width,
        //                        Height = orderView.Height,
        //                    };

        //                    orderWindow.Show();
        //                    await Task.Delay(50); // 添加延迟，避免短时间内同时显示多个窗口
        //                }
        //            });

        //            if (longHuView.Count > 0)
        //            {
        //                tasks.Add(MainViewModel.CreateLongHuViewAsync(longHuView[0]));
        //            }

        //            if (onHoldView.Count > 0)
        //            {
        //                tasks.Add(MainViewModel.CreateOnHoldViewAsync(onHoldView[0]));
        //            }

        //            if (messageView.Count > 0)
        //            {
        //                tasks.Add(MainViewModel.ChatMessageViewAsync(messageView[0]));
        //            }

        //            // 等待所有任务完成
        //            await Task.WhenAll(tasks);
        //        }
        //    }
        //    catch (Exception ex)
        //    {
        //        HandyControl.Controls.MessageBox.Show("加载窗口位置配置失败：" + ex.Message);
        //    }
        //}


        public async Task CreateChatMessageViewAsync(WindowPosition position = null)
        {
            if (_chatMessageView == null)
            {
                if (position != null)
                {
                    _chatMessageView = new ChatMessageAdminWindow
                    {
                        Title = $"{UserHelper.NickName}-聊天窗口",
                        //WindowStartupLocation = WindowStartupLocation.CenterScreen; // 设置窗口启动位置为屏幕中央
                        Left = position.Left,
                        Top = position.Top,
                        Width = position.Width,
                        Height = position.Height,
                    };
                }
                else
                {
                    _chatMessageView = new ChatMessageAdminWindow
                    {
                        Title = $"{UserHelper.NickName}-聊天窗口",
                        WindowStartupLocation = WindowStartupLocation.CenterScreen // 设置窗口启动位置为屏幕中央
                    };
                }

                await Task.Run(() =>
                {
                    // 模拟一些需要后台执行的初始化操作
                    System.Threading.Thread.Sleep(50); // 模拟延迟
                });


                await Application.Current.Dispatcher.InvokeAsync(() =>
                {
                    _chatMessageView.Show();
                });
            }
            else
            {
                // 如果窗口已经显示，则检查窗口状态
                if (_chatMessageView.WindowState == WindowState.Minimized)
                {
                    // 如果窗口最小化，则先将其恢复正常状态
                    _chatMessageView.WindowState = WindowState.Normal;
                }
                // 然后再将窗口置顶显示
                _chatMessageView.Activate(); // 激活置顶
            }
        }
    }
}
